#! /usr/bin/python

import socket, re
import string
import sys

cookieDict = {}
cookie = ""
userName = ""
passWord = ""
attendType = 0
attendTypeStr = ["mswt", "mewt", "aswt", "aewt"]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

logrequest = """\r\nCache-Control: no-cache\r\nOrigin: http://oa.nfschina.com:9001\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11 CoolNovo/2.0.1.40\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nReferer: http://oa.nfschina.com:9000/Login_logout.action\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: zh-CN,zh;q=0.8\r\nAccept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n\r\n"""

taskrequest = """GET /task.action?method:showTodayTasks HTTP/1.1\r\n\
Host: oa.nfschina.com:9001\r\n\
Connection: keep-alive\r\n\
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko)\
Chrome/17.0.963.56 Safari/535.11 CoolNovo/2.0.1.40\r\n\
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n\
Referer: http://oa.nfschina.com:9001/Login_main.action\r\n\
Accept-Encoding: gzip,deflate,sdch\r\n\
Accept-Language: zh-CN,zh;q=0.8\r\n\
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n\
Cookie: """

attendancerequest = """POST /attendance.action?method:workTime HTTP/1.1\r\n\
Host: oa.nfschina.com:9001\r\n\
Connection: keep-alive\r\n\
Content-Length: 9\r\n\
Origin: http://oa.nfschina.com:9001\r\n\
X-Requested-With: XMLHttpRequest\r\n\
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko)\
Chrome/17.0.963.56 Safari/535.11 CoolNovo/2.0.1.40\r\n\
Content-Type: application/x-www-form-urlencoded\r\n\
Accept: application/json, text/javascript, */*\r\n\
Referer: http://oa.nfschina.com:9001/task.action?method:showTodayTasks\r\n\
Accept-Encoding: gzip,deflate,sdch\r\n\
Accept-Language: zh-CN,zh;q=0.8\r\n\
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n\
Cookie: """

def readSocket(s):
    recvContent = ""
    responce = s.recv(8192)
    while responce:
        recvContent += responce
        #print responce
        if recvContent.find("\r\n0\r\n\r\n") != -1:
            break
        m = re.search("Content-Length:\s*(\d+)", recvContent)
        if m:
            contentLen = string.atoi(m.group(1))
            headerEnd = recvContent.find("\r\n\r\n")
            if headerEnd != -1:
                headerEnd += 4
                recvedData = len(responce) - headerEnd
                if recvedData >= contentLen:
                    break;
        responce = s.recv(8192)
    return recvContent

def init():
    if (len(sys.argv) < 2):
        print "missing username"
        sys.exit(0)
    global userName
    global passWord
    userName += sys.argv[1]

    if len(sys.argv) > 2:
        passWord += sys.argv[2]
    else:
        passWord += "1234"

    print userName, ", ", passWord
    if len(sys.argv) == 4:
        attendType = string.atoi(sys.argv[3])
    global s
    s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1);
    #s.setblocking(0)
    s.connect((socket.gethostbyname("oa.nfschina.com"), 9001))
    print "connected"

def tear_down():
    global s
    s.close()



def doLog(usrname, password):
    content = "user.account=" +usrname + \
            "%40nfschina.com&user.password=" + password + "&usercheck=on"

    header = """POST /Login_main.action HTTP/1.1\r\nHost: oa.nfschina.com:9001\r\nConnection: keep-alive\r\nContent-Length: """
    header += str(len(content)); header += logrequest; header += content
    #print header

    global s
    s.send(header)
    #s.shutdown(1)
    print "recving in log..."
    responce = readSocket(s)
    m = re.search("Set-Cookie: .*\r\n", responce)
    if (m):
        cookiestr = responce[m.start():m.end()]
        for mm in re.compile("(\S+)=([^; \r\n]+)").finditer(cookiestr):
            cookieDict[mm.group(1)] = mm.group(2)
    else:
        print "can't find cookie"

def getTask(usrname, password):
    global cookie
    global taskrequest
    requst = taskrequest
    if cookieDict.has_key("JSESSIONID"):
        sessioncookie = "JSESSIONID" + "=" + cookieDict["JSESSIONID"]
        cookie += (sessioncookie + "; ")
    usrpassCookie = "imoneusername="+usrname+"@nfschina.com; imonepassword=" + password
    cookie += usrpassCookie; requst += (cookie + "\r\n\r\n")
    #print requst
    s.send(requst)
    readSocket(s)
#    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#    #s.setblocking(0)
#    s.connect((socket.gethostbyname("oa.nfschina.com"), 9001))
#    print "connected in gettask"
#    s.send(requst)
#    s.shutdown(1)
#    print "recving from gettask..."
#    responce = s.recv(8192)
#    while responce:
#        print responce
#        responce = s.recv(8192)

def attendance(wtstr):
    global cookie
    global attendancerequest
    requst = attendancerequest
    requst += (cookie + "\r\n\r\n")
    content = "time="+ wtstr; requst += content
    #print requst
    s.send(requst)
    readSocket(s)


init()
#log on
doLog(userName, passWord)

print cookieDict
#get the task information
getTask(userName, passWord)

#click the button
attendance(attendTypeStr[attendType])

tear_down()
